CC = "cc"
AR = "ar"

if ENV["DEBUG"]
  CC_FLAGS = ENV["CC_FLAGS"] || "-std=gnu99 -O0 -g4 -D_ASSERT_USED -D_ERROR_PRINT"
else
  CC_FLAGS = ENV["CC_FLAGS"] || "-std=gnu99 -O3 -D_ERROR_PRINT"
end

static_lib = "lib/libh264bsd.a"
test_app = "bin/test_h264bsd"

directory "obj"
directory "bin"
directory "lib"
directory "include"
directory "../test/output"

# Convert .c file in ../src to .o file in obj
rule ".o" => ->(o_file) {[o_file.gsub(/o$/, 'c').gsub("obj/", "../src/"), "obj"]} do |t|
  sh "#{CC} #{t.source} -c #{CC_FLAGS} -o #{t.name}"
end

# Use all .c files in the ../src directory
o_files = FileList["../src/*.c"].gsub(/c$/, 'o').gsub("../src/", "obj/")

# Copy all .h files in the ../src directory
h_files = FileList["../src/*.h"].gsub("../src/", "include/")

# Build static lib
file static_lib => o_files + ["lib"] do |t|
  sh "#{AR} rcs #{static_lib} #{o_files.join(' ')}"
end

# Copy header files
rule /include\/.*\.h/ => ->(dst) { [dst.gsub("include/", "../src/"), "include"] } do |t|
  FileUtils.cp t.source, t.name, :verbose => true
end

task :static_lib => h_files + [static_lib]

# Build test application
file test_app => [:static_lib, "test_h264bsd.c", "bin"] do |t|
  sh "#{CC} test_h264bsd.c #{CC_FLAGS} -Llib -lh264bsd -o #{test_app}"
end

# Run test application
task :test => [test_app] do |t|
  sh "#{test_app} ../test/test_1920x1080.h264"
end

# Run test application
task :test_640x360 => [test_app] do |t|
  sh "#{test_app} ../test/test_640x360.h264"
end

# Run test application decoding repeatedy until stopped
task :test_repeat => [test_app] do |t|
  sh "#{test_app} -r ../test/test_1920x1080.h264"
end

# Run test application and compare to test/output
task :test_compare => [test_app] do |t|
  sh "#{test_app} -c ../test/test_1920x1080.yuv ../test/test_1920x1080.h264"
end

# Run test application decoding repeatedy until stopped
task :test_output => [test_app] do |t|
  sh "#{test_app} -o ../test/test_1920x1080_posix.yuv ../test/test_1920x1080.h264"
end

task :clean do
  FileUtils.rm_rf("obj")
  FileUtils.rm_rf("bin")
  FileUtils.rm_rf("lib")
  FileUtils.rm_rf("include")
end

task :default => [:static_lib]
